
package bd_jugueteria;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class Proveedor extends javax.swing.JFrame {
 
       private final ventana principal;
                    Connection conector;
    
    public Proveedor(ventana v, Connection c) throws SQLException {
        initComponents();
         
        principal = v;
        conector = c;
        
         Statement st = conector.createStatement();
        
        
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TProveedor = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jTextField4 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Proveedor");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        TProveedor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(TProveedor);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 59, 630, 194));

        jButton1.setFont(new java.awt.Font("Papyrus", 3, 11)); // NOI18N
        jButton1.setText("Eliminar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 271, -1, -1));

        jButton2.setFont(new java.awt.Font("Papyrus", 3, 11)); // NOI18N
        jButton2.setText("Actualizar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 270, -1, -1));

        jLabel1.setFont(new java.awt.Font("Comic Sans MS", 3, 12)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Nombre");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 270, 68, 23));

        jLabel2.setFont(new java.awt.Font("Comic Sans MS", 3, 12)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Estado");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 280, -1, -1));

        jLabel3.setFont(new java.awt.Font("Comic Sans MS", 3, 12)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Telefono");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 280, -1, -1));
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 320, 83, -1));
        getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 320, 79, -1));
        getContentPane().add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 320, 89, -1));

        jButton3.setFont(new java.awt.Font("Papyrus", 3, 11)); // NOI18N
        jButton3.setText("VOLVER");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 320, 100, 31));

        jButton4.setFont(new java.awt.Font("Papyrus", 3, 11)); // NOI18N
        jButton4.setText("Agregar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 320, -1, -1));

        jButton5.setFont(new java.awt.Font("Papyrus", 3, 11)); // NOI18N
        jButton5.setText("Buscar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(42, 18, -1, -1));
        getContentPane().add(jTextField4, new org.netbeans.lib.awtextra.AbsoluteConstraints(136, 19, 98, -1));

        jLabel4.setBackground(new java.awt.Color(153, 153, 255));
        jLabel4.setForeground(new java.awt.Color(153, 153, 255));
        jLabel4.setOpaque(true);
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(2, 5, 660, 400));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        
        int fila2 = TProveedor.getSelectedRow();
        
        if(jButton2.getText().equals("Actualizar")){
        if (fila2 >= 0) {
            //jug1.setText(Tjuguete.getValueAt(fila2, 0).toString());
            jTextField1.setText(TProveedor.getValueAt(fila2, 1).toString());
            jTextField2.setText(TProveedor.getValueAt(fila2, 2).toString());
            jTextField3.setText(TProveedor.getValueAt(fila2, 3).toString());
            
            jButton2.setText("Guardar cambios");
            
        } else {
            JOptionPane.showMessageDialog(null, "Seleccionado una fila por favor");
        }
        
            
        }
        else{
            
          jButton2.setText("Actualizar");
        
         try {

            PreparedStatement pre = conector.prepareStatement("UPDATE proveedores "
                    + "SET nombre='" + jTextField1.getText() + "', estado='" + jTextField2.getText() 
                    + "',telefono='" + jTextField3.getText()+
                     "' WHERE idproveedor='" + TProveedor.getValueAt(fila2, 0).toString() + "';");
            pre.executeUpdate();;
            pre.executeUpdate();

            
            jTextField1.setText("");
            jTextField2.setText("");
            jTextField3.setText("");
            
            JOptionPane.showMessageDialog(this, "Se Actualizo Proveedor con Exito");
            MostrarProveedor("");
        } catch (SQLException ex) {
            //JOptionPane.showMessageDialog(this, "Error al Corregir");
            System.out.print(ex.getMessage());
        }
        }                      
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        if(jTextField1.getText().length()>0 && jTextField2.getText().length()>0 &&jTextField3.getText().length()>0 && jButton2.getText().equals("Actualizar"))
        {
            
        try (PreparedStatement insertar = conector.prepareStatement("insert into "
                    + "proveedores(nombre, estado, telefono) "
                    + " values(?,?,?)")) {
                insertar.setString(1, jTextField1.getText());
                insertar.setString(2, jTextField2.getText());
                insertar.setString(3, jTextField3.getText());
                insertar.execute();
                insertar.close();
                JOptionPane.showMessageDialog(null, "Proveedor Agregado");

                Statement st = conector.createStatement();

                ResultSet r = st.executeQuery("Select id_proveedor from proveedores order by id_proveedor desc limit 1");
                r.next();
                System.out.println("total aqui: " + r.getString("id_proveedor"));

                MostrarProveedor(r.getString("id_proveedor"));

                jTextField1.setText("");
                jTextField2.setText("");
                jTextField3.setText("");
               
         
        } catch (SQLException e) {
            System.out.print(e.getMessage());
            //JOptionPane.showMessageDialog(null, "ID (" + camp1.getText() + ") en uso..");
        }   
        } 
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
         this.setVisible(false);
        principal.setVisible(true);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        
        MostrarProveedor(jTextField4.getText());
        jTextField4.setText("");
    }//GEN-LAST:event_jButton5ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Proveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Proveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Proveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Proveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
           //     new Proveedor().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable TProveedor;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables


void MostrarProveedor(String prov){
     DefaultTableModel ModeloProveedor = new DefaultTableModel();

       ModeloProveedor.addColumn("ID proveedor");
        ModeloProveedor.addColumn("Nombre");
        ModeloProveedor.addColumn("Estado");
        ModeloProveedor.addColumn("Telefono");
      
        TProveedor.setModel(ModeloProveedor);
        String sql = "";
        if(prov.equals("")){
            
            sql = "SELECT * FROM proveedores";
        }
        else {
         sql = "SELECT * FROM proveedores WHERE idproveedor = '"+prov+"'";
        }
        String[] datosProve = new String[5];
        try {
            Statement st = conector.createStatement();
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()) {
                datosProve[0] = rs.getString(1);
                datosProve[1] = rs.getString(2);
                datosProve[2] = rs.getString(3);
                datosProve[3] = rs.getString(4);

                ModeloProveedor.addRow(datosProve);

            }
            TProveedor.setModel(ModeloProveedor);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }

}
}
